// 初始化整个游戏的精灵，作为游戏开发的入口
import {ResourceLoader} from "./base/resourceLoader.js";
import {Director} from "./director.js";
import {BackGround} from "./runtime/backGround.js";
import { Land } from "./runtime/land.js";
import {DataStore} from "./base/dataStore.js";
import {Birds} from "./player/birds.js";
import { StartButton } from "./player/startButton.js";
import { Score } from "./player/score.js";
import { ApiExamples } from "./ApiExamples.js";

export class Main{
  constructor(){
    this.canvas = wx.createCanvas();
    this.ctx = this.canvas.getContext('2d');
    this.dataStore = DataStore.getInstance();
    this.Director = Director.getInstance();
    // 直接调用 ResourceLoader类的static 方法create 等同于
    // new ResourceLoader();
    const loader = ResourceLoader.create();
    loader.onLoaded(map => this.onResourceFirstLoader(map))
  }

  //创建背景音乐
  createBackgroundMusic() {
    const bgm = wx.createInnerAudioContext();
    bgm.autoplay = true;
    bgm.loop = true;
    // bgm.src = 'audio/bgm.mp3';
  }

  onResourceFirstLoader(map){
    this.dataStore.canvas = this.canvas;
    this.dataStore.ctx = this.ctx;
    this.dataStore.res = map;
    this.createBackgroundMusic();
    const examples = new ApiExamples();
    // examples.getUserInfo();
    // examples.login();
    // examples.getSettings();
    // examples.httpExample();
    // examples.socketExample();
    // examples.download();

    // // 首先重置游戏是是结束的
    this.Director.isGameHasStart = false;
    this.Director.isGameOver = false;
    this.init();
  }

  init(){

    this.dataStore
      .put('pencils', [])
      .put('background', BackGround)
      .put('land', Land)
      .put('birds', Birds)
      .put('score', Score)
      .put('startButton', StartButton);
    // 要在游戏逻辑运行之前
    this.registerEvent();
    this.Director.createPencil();
    this.Director.run();
  }

  registerEvent() {
    // this.canvas.addEventListener('touchstart', e => {
    //     //屏蔽掉JS的事件冒泡
    //     e.preventDefault();
    //     if (this.Director.isGameOver) {
    //         console.log('游戏开始');
    //         this.init();
    //     } else {
    //         this.Director.birdsEvent();
    //     }
    // });

    wx.onTouchStart(() => {
      if (this.Director.isGameOver || !this.Director.isGameHasStart) {
        this.Director.isGameOver = false;
        this.Director.isGameHasStart = true;
        console.log('游戏开始');
        // 这里会在状态切换时，初始化
        this.init();
      } else {
        this.Director.birdsEvent();
      }
    });
  }
}